import { defineStore } from "pinia";
import { ref, computed, watch } from "vue";
import { useUserStore } from "./useUserStore";
import { useBindingStore } from "./useBindingStore";
import { get } from '@/utils/request.js';

export const useHealthData = defineStore("healthData", () => {
  const bindingStore = useBindingStore();
  const userStore = useUserStore();
  
  // 初始化 curUserId 为 null，等待绑定列表加载
  const curUserId = ref(null);
  
  // 监听绑定列表变化
  watch(() => bindingStore.getBindingList, (newList) => {
    if (newList && newList.length > 0) {
      // 如果有绑定列表，使用第一个绑定的老人ID
      curUserId.value = newList[0].id;
    }
  }, { immediate: true });
  
  // 监听当前选中的绑定ID变化
  watch(() => bindingStore.getCurBindingId, (newId) => {
    if (newId) {
      curUserId.value = newId;
    }
  }, { immediate: true });

  const setCurUserId = (id) => {
    if (id) {
      curUserId.value = id;
    }
  };
  
  const getCurUserId = computed(() => curUserId.value);

  const realtimeHealthData = ref({
    id: 1,
    healthStatus: "normal",
    heartRate: 60,
    bloodOxygen: 98,
    bloodPressureHigh: 120,
    bloodPressureLow: 70,
    bodyTemperature: 36.6,
    otherData: {},
    collectTime: "2025-05-23T12:02:29.000Z",
  });

  const heartRateDetailData = ref({
    daily: null,
    weekly: null
  });

  const bloodPressureDetailData = ref({
    daily: null,
    weekly: null
  });

  const bloodOxygenDetailData = ref({
    daily: null,
    weekly: null
  });

  const sleepDetailData = ref({
  
  });

  const activityDetailData = ref({
  });

  const getRealtimeHealthData = computed(() => {
    return realtimeHealthData.value;
  });

  const fetchRealtimeData = async (userId) => {
    if(!userId){
        // userId = userStore.getUserId;
        userId = curUserId.value;
    }

    console.log('fetchRealtimeData userId:', userId)
    try{
        let res = await get(`/health/${userId}/real-time`, "api/v1");
        if(res?.code === 200){
            console.log("get realtime healthData:",res.data);
            realtimeHealthData.value = res.data;
        }else{
            throw new Error("In Realtime-HealthData:",res?.msg);
        }

        return res.data;
    }
    catch(error){ 
        console.error("Error fetching realtime data:", error);
        throw error;
    }
  };

  // 新增详情页面数据获取方法
  const fetchHeartRateDetail = async (userId, period = 'day') => {
    try {
      const res = await get(`/health/${userId}/statistics?period=${period}&type=heartRate`, 'api/v1');
      if (res?.code === 200) {
        heartRateDetailData.value[period] = res.data;
        return res.data;
      }
      throw new Error(res?.msg || '获取心率详情数据失败');
    } catch (error) {
      console.error('Error fetching heart rate detail:', error);
      throw error;
    }
  };

  const fetchSleepDetail = async (userId, period = 'day') => {
    try {
      const res = await get(`/sleep/${userId}/statistics?period=${period}`, 'api/v1');
      if (res?.code === 200) {
        sleepDetailData.value[period] = res.data;
        // console.log("get sleep detail data:", res.data);  
        return res.data;
      }
      throw new Error(res?.msg || '获取睡眠详情数据失败');
    } catch (error) {
      console.error('Error fetching sleep detail:', error);
      throw error;
    }
  };

  const fetchActivityDetail = async (userId, period = 'day') => {
    try {
      const res = await get(`/activity/${userId}/statistics?period=${period}`, 'api/v1');
      if (res?.code === 200) {
        activityDetailData.value[period] = res.data;
        // console.log("get activity detail data:", res.data);
        return res.data;
      }
      throw new Error(res?.msg || '获取活动详情数据失败');
    } catch (error) {
      console.error('Error fetching activity detail:', error);
      throw error;
    }
  };

  const fetchBloodPressureDetail = async (userId, period = 'day') => {
    try {
      const res = await get(`/health/${userId}/statistics?period=${period}&type=bloodPressure`, 'api/v1');
      if (res?.code === 200) {
        bloodPressureDetailData.value[period] = res.data;
        return res.data;
      }
      throw new Error(res?.msg || '获取血压详情数据失败');
    } catch (error) {
      console.error('Error fetching blood pressure detail:', error);
      throw error;
    }
  };

  const fetchBloodOxygenDetail = async (userId, period = 'day') => {
    try {
      const res = await get(`/health/${userId}/statistics?period=${period}&type=bloodOxygen`, 'api/v1');
      if (res?.code === 200) {
        bloodOxygenDetailData.value[period] = res.data;
        return res.data;
      }
      throw new Error(res?.msg || '获取血氧详情数据失败');
    } catch (error) {
      console.error('Error fetching blood oxygen detail:', error);
      throw error;
    }
  };

  // 新增计算属性
  const getSleepDetailData = computed(() => sleepDetailData.value);
  const getActivityDetailData = computed(() => activityDetailData.value);
  const getHeartRateDetailData = computed(() => heartRateDetailData.value);
  const getBloodPressureDetailData = computed(() => bloodPressureDetailData.value);
  const getBloodOxygenDetailData = computed(() => bloodOxygenDetailData.value);

  const setRealtimeHealthData = (data) => {
    realtimeHealthData.value = data;
  };

  return {
    // 直接返回ref对象
    realtimeHealthData,
    // 计算属性
    getRealtimeHealthData,
    setRealtimeHealthData,
    // 方法
    fetchRealtimeData,
 
    curUserId,
    getCurUserId,
    setCurUserId,

    sleepDetailData,
    activityDetailData,
    heartRateDetailData,
    bloodPressureDetailData,
    bloodOxygenDetailData,
    
    getSleepDetailData,
    getActivityDetailData,
    getHeartRateDetailData,
    getBloodPressureDetailData,
    getBloodOxygenDetailData,
    fetchSleepDetail,
    fetchActivityDetail,
    fetchHeartRateDetail,
    fetchBloodPressureDetail,
    fetchBloodOxygenDetail
  };
});
